<!doctype html>
<html>
<meta charset="UTF-8">
<head>
    <title>Statistics</title>
    <style>
        li {
            list-style: none;
        }

    </style>
</head>
<body>
<div style="width:30%;padding: 25px;">
    <div>
        数据展示为最近7天,图表精度1个小时<br/>
        total = 服务端对连接的客户端发送通知栏消息总数<br/>
        success = 客户端收到通知栏消息后,发包给服务器,10秒内记成功<br/>
        latency = 服务器发通知的时候,加上服务器时间戳,客户端回包加上这个时间戳,计算延迟,10秒外计算为失败<br/>
        average latency = sum(latency) / success<br/>
        success rate = success/total<br/>
    </div>
    <br/>

    <div>
        key :<input id="key" value="" type="hidden">
        <ul>
        </ul>
    </div>
    <br/>

    <div>
        SessionCount: <span id="sessionCount">0</span><br/>
        ios: <span id="iosSessionCount">0</span><br/>
        android: <span id="androidSessionCount">0</span><br/>
        Total Count: <span id="totalCount">0</span><br/>
        Success Rate(percent): <span id="successRate">0</span><br/>
        Average Latency(ms): <span id="avgLatency">0</span><br/>
        Per Second: <span id="requestPerSecond">0</span><br/>
    </div>
    <br/>
    <br/>

    <div>
        <label for="totalChartHour">
            Total Count(Hour)<br/><br/>
            <canvas id="totalChartHour" height="300" width="800"></canvas>
        </label>
    </div>

    <div>
        <label for="totalChartDay">
            Total Count(Day)<br/><br/>
            <canvas id="totalChartDay" height="300" width="800"></canvas>
        </label>
    </div>

    <div>
        <label for="latencyChartHour">
            Latency(ms)(Hour)<br/><br/>
            <canvas id="latencyChartHour" height="400" width="800"></canvas>
        </label>
    </div>

    <div>
        <label for="latencyChartDay">
            Latency(ms)(Day)<br/><br/>
            <canvas id="latencyChartDay" height="400" width="800"></canvas>
        </label>
    </div>

    <div>
        <label for="successRateChartHour">
            Success Rate(%)(Hour)<br/><br/>
            <canvas id="successRateChartHour" height="400" width="800"></canvas>
        </label>
    </div>

    <div>
        <label for="successRateChartDay">
            Success Rate(%)(Day)<br/><br/>
            <canvas id="successRateChartDay" height="400" width="800"></canvas>
        </label>
    </div>

</div>

<script src="/js/jquery-1.8.0.min.js"></script>
<script src="/js/jquery.cookie.js"></script>
<script src="/js/Chart.Core.min.js"></script>
<script src="/js/Chart.Scatter.min.js"></script>

<script>

    function getUrlParameter(sParam) {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                sURLVariables = sPageURL.split('&'),
                sParameterName,
                i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : sParameterName[1];
            }
        }
    }
    ;

    var options = {
        animation: false,
        bezierCurve: true,
        pointDot: false,
        showTooltips: true,
        scaleShowHorizontalLines: true,
        scaleShowLabels: true,
        scaleType: "date",
        tooltipTemplate: "<%=valueLabel%> (<%=argLabel%>)",
        scaleDateFormat: "mm-dd",
        scaleTimeFormat: "HH:MM",
        scaleDateTimeFormat: "mm-dd HH:MM"
    };

    var optionsDay = {
        animation: false,
        bezierCurve: true,
        pointDot: true,
        showTooltips: true,
        scaleShowHorizontalLines: true,
        scaleShowLabels: true,
        scaleType: "date",
        tooltipTemplate: "<%=valueLabel%> (<%=argLabel%>)",
        scaleDateFormat: "mm-dd",
        scaleTimeFormat: "mm-dd",
        scaleDateTimeFormat: "mm-dd"
    };

    function loadData() {
        $.ajax({
            type: 'GET',
            url: "https://" + window.location.hostname + ":" + $.cookie("api_port") + '/api/stats/chart',
            data: {key: $("#key").val()},
            dataType: 'json',
            success: function (data) {

                $("#totalCount").text(data.totalCount);
                $("#avgLatency").text(data.avgLatency);
                $("#successRate").text((data.successRate * 100).toFixed(3) + '%');

                makeChart("totalChartHour", "count", data.chartData.total, data.chartData.timestamps);
                makeDayChart("totalChartDay", "count", data.chartData.total, data.chartData.timestamps);

                    makeChart("latencyChartHour", "count", data.chartData.latency, data.chartData.timestamps);
                makeDayChart("latencyChartDay", "count", data.chartData.latencyDay, data.chartData.timestamps);

                makeChart("successRateChartHour", "percent", data.chartData.successRate, data.chartData.timestamps);
                makeDayChart("successRateChartDay", "percent", data.chartData.successRateDay, data.chartData.timestamps);
            }
        });

        $.ajax({
            type: 'GET',
            url: "https://" + window.location.hostname + ":" + $.cookie("api_port") + '/api/stats/base',
            success: function (data) {
                $("#sessionCount").text(data.sessionCount);
                $("#iosSessionCount").text(data.ios);
                $("#androidSessionCount").text(data.android);
            }
        });
    }

    function loadQueryDataKeys() {
        $.ajax({
            type: 'GET',
            url: "https://" + window.location.hostname + ":" + $.cookie("api_port") + '/api/stats/getQueryDataKeys',
            success: function (data) {
                var result = data.result;
                for (var i = 0; i < result.length; i++) {
                    $("#key").append("<option value='" + result[i] + "'> " + result[i] + "</option>");
                    var $li_1 = $("<li><a href='#' text='" + result[i] + "' class='keys'>" + result[i] + "</a></li>");
                    $("ul").append($li_1);
                }
                if (result.length > 0) {
                    $("#key").val(result[0])
                    loadData();
                }

                $('.keys').click(function () {
                    $("#key").val($(this).attr("text"));
                    loadData();
                });
            }
        });
    }

    window.onload = function () {
        loadQueryDataKeys();
    }

    function makeDayChart(canvas, name, serverData, timestamps) {
        var chart = document.getElementById(canvas).getContext("2d");
        var data = convertDay(name, serverData, timestamps);
        new Chart(chart).Scatter(data, optionsDay);
    }

    function makeChart(canvas, name, serverData, timestamps) {
        var chart = document.getElementById(canvas).getContext("2d");
        var data = convert(name, serverData, timestamps);
        new Chart(chart).Scatter(data, options);
    }

    function convertDay(name, serverData, timestamps) {
        var chartData = [
            {
                label: name,
                fillColor: "rgba(151,187,205,0.2)",
                strokeColor: "rgba(151,187,205,1)",
                pointColor: "rgba(151,187,205,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: []
            }];
        var dayTotal = 0;
        for (var i = 0; i < timestamps.length; i++) {
            if (serverData.length != 7) {
                dayTotal += serverData[i];
            } else {
                console.log("xxx " + Math.floor(i / 24));
                dayTotal = serverData[Math.floor(i / 24)];
            }
            if ((i + 1) % 24 == 0) {

                chartData[0].data.push({x: new Date(timestamps[i - 23]), y: dayTotal});
                dayTotal = 0;
            }
        }
        return chartData;
    }

    function convert(name, serverData, timestamps) {
        var offset = new Date().getTimezoneOffset() * 60 * 1000 * -1;
        var chartData = [
            {
                label: name,
                fillColor: "rgba(151,187,205,0.2)",
                strokeColor: "rgba(151,187,205,1)",
                pointColor: "rgba(151,187,205,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: []
            }];
        for (var i = 0; i < timestamps.length; i++) {
            chartData[0].data.push({x: new Date(timestamps[i] + offset), y: serverData[i]});
        }
        return chartData;
    }

</script>
</body>
</html>
